//
//  StatisticsPieChartCell.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/11/1.
//

import UIKit
import Charts
import SnapKit
import ETKit

let kPieChartViewHeight: CGFloat = 500

class StatisticsPieChartCell: BaseTableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        
        setupUI()
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        
        setupUI()
    }
    
    private func setupUI() {
        selectionStyle = .none
        backgroundColor = .clear
        
        contentView.addSubview(totalTime)
        totalTime.snp.makeConstraints { make in
            make.top.equalTo(contentView)
            make.left.right.equalTo(contentView)
            make.height.equalTo(40)
        }
        
        contentView.addSubview(pieChartView)
        pieChartView.snp.makeConstraints { make in
            make.top.equalTo(totalTime).offset(5)
            make.left.right.equalTo(contentView)
            make.height.equalTo(kPieChartViewHeight)
        }
        
        setData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: .refreshPieChart, object: nil)
    }
    
    @objc private func refresh() {
        setData()
    }
    
    private func getDatas() -> [StatisticsModel] {
        let type = Global.shared.currentStatisticsYTD
        
        switch type {
        case .daily:
            guard let t = DateUtil.dateRange(date: Date(), direction: .this(range: .day)) else { return [StatisticsModel]() }
            return TimeStatisticsStore.queryGroupDuration(start: t.start, end: t.end)
        case .weekly:
            guard let t = DateUtil.dateRange(date: Date(), direction: .this(range: .week)) else { return [StatisticsModel]() }
            return TimeStatisticsStore.queryGroupDuration(start: t.start, end: t.end)
        case .month:
            guard let t = DateUtil.dateRange(date: Date(), direction: .this(range: .month)) else { return [StatisticsModel]() }
            return TimeStatisticsStore.queryGroupDuration(start: t.start, end: t.end)
        case .all:
            return TimeStatisticsStore.queryGroupDuration()
        }
    }
    
    private func setData() {
        let datas = getDatas()

        var colors = [UIColor]()
        var yVals = [PieChartDataEntry]()
        var legendEntrys = [LegendEntry]()
        var totalT: TimeInterval = 0
        
        for statistics in datas {
            let title = statistics.customTimer?.name ?? "未知"
            let color = statistics.customTimer?.color ?? .label
            let content = "\(title)\n\(statistics.sum.et.formatHMS())"
            let legendEntry = LegendEntry(label: content) // 说明标签
            let entry = PieChartDataEntry(value: statistics.sum, label: title) // 扇区数据
            legendEntry.formColor = color
            yVals.append(entry)
            colors.append(color)
            legendEntrys.append(legendEntry)
            totalT = totalT + statistics.sum
        }
        totalTime.text = "总计：\(totalT.et.formatHMS())"
        
        // 自定义说明标签数据
        let legend = pieChartView.legend
        legend.setCustom(entries: legendEntrys)

        let set = PieChartDataSet(entries: yVals, label: "rrrr")
        set.colors = colors
        set.entryLabelFont = UIFont.systemFont(ofSize: 11)
//        set.entryLabelColor = .black
        set.drawValuesEnabled = true; // 是否在拐点处显示数据
//        set.valueColors = colors
//        set.xValuePosition = .outsideSlice; // 名称位置
        set.xValuePosition = .insideSlice; // 名称位置
//        set.yValuePosition = .insideSlice; // 数据位置 // 折线是否显示
        set.yValuePosition = .outsideSlice; // 数据位置 // 折线是否显示
        set.valueLineColor = .label // 折线颜色
        set.sliceSpace = 0; // 相邻区块之间的间距
        set.selectionShift = 5; // 扇形区域放大范围

        let data = PieChartData(dataSet: set)
        data.setValueFont(.systemFont(ofSize: 14))
        data.setValueTextColor(.label)
        pieChartView.data = data;

        // 格式化要在data之后，否则无法生效
        let pFormatter = NumberFormatter()
        pFormatter.numberStyle = .percent
        pFormatter.maximumFractionDigits = 1
        pFormatter.multiplier = 1
        pFormatter.percentSymbol = "%"
        data.setValueFormatter(DefaultValueFormatter(formatter: pFormatter))
        
        pieChartView.animate(xAxisDuration: 2.0, easingOption: .easeOutExpo)
    }
    
    private lazy var totalTime: UILabel = {
        let l = UILabel()
        l.textAlignment = .center
        l.font = UIFont.systemFont(ofSize: 16)
        return l
    }()
    
    private lazy var pieChartView: PieChartView = {
        let pieChart = PieChartView()
        pieChart.backgroundColor = .clear

//        pieChartView.centerText = "数据分析"
        // 是否显示中间圆
        pieChart.drawHoleEnabled = false
        // 将数据转换为百分比
        pieChart.usePercentValuesEnabled = true

        pieChart.chartDescription.enabled = true
//        pieChart.chartDescription.text = "耗时统计";

        // 拖拽饼状图后是否有惯性效果
        pieChart.dragDecelerationEnabled = true
        pieChart.drawSlicesUnderHoleEnabled = true

        // 饼状图距离边缘的间隙
        pieChart.setExtraOffsets(left: 30, top: 0, right:30, bottom: 30)

        let l = pieChart.legend
        l.horizontalAlignment = .left
        l.verticalAlignment = .bottom
        l.orientation = .horizontal
        l.drawInside = false
        l.xEntrySpace = 7
        l.yEntrySpace = 15
        l.yOffset = 10
        
        return pieChart
    }()
}
